/**
 * Created by chenxq on 2017/12/18.
 */
import React, { PureComponent ,Component} from 'react';
import { Table, Button, Input, message, Popconfirm, Divider, Select,Radio} from 'antd';
import styles from './style.less';
import request from '../../utils/request';
import uuid from '../../utils/uuid';
import {findObjByKey ,convertLongToString} from '../../utils/index';

const {Option} = Select;
const RadioGroup = Radio.Group;


export default class TableForm extends PureComponent {

  static defaultProps={
    get:'',
    add:'',
    remove:'',
    edit:'',
    columns:[],
    defaultObj:{},
    title:'新增其他联系方式'
  }
  constructor(props){
    super(props);
    let columns=this.getColumns();
    this.state={
      list:[],
      columns:columns
    }
  }

  getColumns=()=>{
    let {columns} = this.props;
    let arr=[];
    columns.forEach(item=>{
      let obj={
        title:item.title,
        dataIndex:item.dataIndex,
        render:(val,record)=>{
          switch (item.type){
            case 'select' :
              if(record.editable){
                return <Select value={val || item.data[0].key}
                               style={{width:'80px'}}
                               onChange={val => this.handleFieldChange(val, item.dataIndex, record.key)}


                >
                  {(item.data || []).map(one=><Option key={one.key} value={one.key}>{one.name}</Option>)}
                </Select>
              }else{
                return val ? findObjByKey(item.data,val).name : ''

              }; break;
            case 'radio':
              if(record.editable){
                return <RadioGroup onChange={e => this.handleFieldChange(e.target.value, item.dataIndex, record.key)} value={val || item.data[0].key}>
                  {(item.data || []).map(one=><Radio key={one.key} value={one.key}>{one.name}</Radio>)}
                </RadioGroup>
              }else{
                return val ? findObjByKey(item.data,val):'';
              }

              break;
            default: if(record.editable){
              return <Input placeholder={item.title}
                            value={val || ''}
                            onChange={e => this.handleFieldChange(e.target.value, item.dataIndex, record.key)}
              />
            }
              return val || '';
          }
        }
      }
      arr.push(obj);
    })
    let handel={
      title:'操作',
      key:'action',
      render: (text, record) => {
        if (record.editable) {
          if (record.isNew){
            return (
              <span>
                <a onClick={(e)=>this.save(e,record)}>保存</a>
                <Divider type="vertical" />
                <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}>
                  <a>删除</a>
                </Popconfirm>
              </span>
            );
          }
          return (
            <span>
              <a onClick={(e)=>this.save(e,record)}>保存</a>
              <Divider type="vertical" />
              <a onClick={e =>this.toggleEditable(e, record,false)}>取消</a>
            </span>
          );
        }
        return (
          <span>
            <a onClick={e => this.toggleEditable(e, record,true)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        );
      },
    }
    arr.push(handel);
    return arr;
  }
  // 保存
  save=(e,info)=>{
    e.preventDefault();
    const target = this.getRowByKey(info.key);
    let {columns} = this.props;
    let flag=true;
    columns.forEach(item=>{
      let val=target[item.dataIndex];
      if(item.rules){
        item.rules.map(item=>{
          if(item.required && !val){
            message.error(item.message ||'表单数据错误');
            flag=false;
            return;
          }
          if(val && item.pattern && !item.pattern.test(val)){
            message.error(item.message || '表单数据错误');
            flag=false;
            return ;
          }
        })
      }
      if(!flag){
        return ;
      }
    })
    if(!flag){
      return ;
    }
    let url='';
    let params={...target};
    if(info.isNew){
      // 新增
      url=this.props.add;
      delete params.isNew;
    }else{
      // 编辑
      url=this.props.edit;
    }
    delete params.key;
    let _this=this;
    request(url,{
      method:'POST',
      body:{
        ...params
      }
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('操作成功',0.8,()=>{
          _this.getList();
        })

      }else{
        message.error(jsonData.msg || '获取失败')
      }
    })

  }
  //删除
  remove=(info)=>{
    if(info.isNew){
      const list = this.state.list.filter(item => item.key !== info.key);
      this.setState({ list });
    }else{
      let {remove,keyName}=this.props;
      let _this=this;
      request(remove,{
        method:'POST',
        body:[info[keyName]]
      }).then(jsonData=>{
        if(jsonData.result){
          message.success('删除成功',0.8,()=>{
            _this.getList();
          })
        }else{
          message.error(jsonData.msg || '删除失败');
        }
      })
    }
  }

  handleFieldChange=(val,fieldName,key)=>{
    const newData = [...this.state.list];
    const target = this.getRowByKey(key);
    if (target) {
      target[fieldName] = val;
      this.setState({ list: newData });
    }
  }

  getRowByKey(key) {
    return this.state.list.filter(item => item.key === key)[0];
  }

  toggleEditable=(e,info,editable=true)=>{
    e.preventDefault();
    let target = this.getRowByKey(info.key);
    if(editable==true){
      this.cacheOriginData[info.key]={
        ...target   //记录下来  取消的时候方便还原
      }
    }else{
      if (this.cacheOriginData[info.key]) {
        Object.assign(target, this.cacheOriginData[info.key]);
        delete this.cacheOriginData[info.key];
      }
    }
    target.editable = editable;
    this.setState({ list: [...this.state.list]});
  }
  getList=()=>{
    let {get} = this.props;
    let _this=this;
    request(get).then(jsonData=>{
      if(jsonData.result){
        let list=jsonData.data || [];
        list.forEach(item=>{
          item.key=uuid();
        })
        _this.setState({
          list
        })

      }else{
        message.error(jsonData.msg || '获取失败')
      }
    })
  }
  index = 0;
  cacheOriginData = {};
  addData=()=>{
    let list=[...this.state.list];
    let obj={...this.props.defaultObj};
    obj.key=uuid();
    obj.editable=true;
    obj.isNew=true;
    list.push(obj);
    this.index+=1;
    this.setState({
      list:list
    })

  }
  componentDidMount(){
    this.getList();
  }
  render() {
    const {title} = this.props;
    console.log(this.state.list.length,'list');
    let columns = this.getColumns();
    return (
      <div>
        <Table
          columns={columns}
          dataSource={this.state.list}
          pagination={false}

          rowClassName={(record) => {
            return record.editable ? styles.editable : '';
          }}
        />
        <Button
          style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
          type="dashed"
          onClick={this.addData}
          icon="plus"
        >
          {title}
        </Button>
      </div>
    );
  }
}
